<template>
  <div class="form-page">
    <Card :bordered="false" :dis-hover="true">
      <p slot="title" style="color: #666;">
        <span
          class="iconfont icon-changyongtubiao-xianxingdaochu-zhuanqu-"
          style="font-size: 20px;"
        ></span> 音乐信息
      </p>
      <p slot="extra" style="color: #999;font-size: 12px;">
        <label style="color: #FF3B30;">*</label> 为必填
      </p>

      <div class="company-box">
        <div>
          <Row type="flex" justify="start" align="middle">
            <div class="divider-short"></div>
            基本信息
          </Row>
          <Form
            ref="formModel"
            :rules="ruleValidate"
            :model="bloc.form"
            :label-width="100"
            label-position="right"
          >
            <FormItem label="音乐名:" prop="musicName" required>
              <Input type="text" v-model="bloc.form.musicName" placeholder="请填写音乐名"
                     style="width: 400px;height: 40px;"/>
            </FormItem>
            <FormItem label="音乐英文名:">
              <Input type="text" v-model="bloc.form.englishName" placeholder="请填写音乐英文名" style="width: 400px"/>
            </FormItem>

            <FormItem label="下发指令:">
              <Input type="number" v-model="bloc.form.code" placeholder="下发指令" style="width: 400px"/>
            </FormItem>
            <FormItem label="音频文件:" prop="musicUrl" required>
              <template>
                  <Upload
                    :action="uploadAudio"
                    :headers="uploadHeaders"
                    :on-success="audioHandleSuccess"
                  >
                    <Button icon="ios-cloud-upload-outline" style="color:#dcdee2;">上传文件</Button>
                  </Upload>
              </template>
            </FormItem>
            <FormItem label="图片文件:" prop="imgUrl" required>
              <div class="demo-upload-list" v-for="(item, index) in fileList" :key="item.modelIcon">
                <template v-if="item.status === 'finished'">
                  <img :src="item.modelIcon">
                  <div class="demo-upload-list-cover">
                    <Icon type="ios-eye-outline" @click.native="handleView(item.modelIcon)"></Icon>
                    <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                  </div>
                </template>
              </div>
              <Upload
                ref="upload"
                :show-upload-list="false"
                :action="uploadAudio"
                :max-size="50"
                :format="['jpg','png']"
                :headers="uploadHeaders"
                :on-format-error="handleFormatError"
                :on-exceeded-size="handleMaxSize"
                :on-success="imgHandleSuccess"
                :before-upload="handleBeforeUpload"
                type="drag"
                style="display: inline-block;width:58px;margin-left:15px"
              >
                <div style="width: 58px;height:58px;line-height: 58px;">
                  <Icon type="ios-camera" size="20"></Icon>
                </div>
                <Modal title="View Image" v-model="visible">
                  <img :src="imgUrl" v-if="visible" style="width: 100%">
                </Modal>
              </Upload>
              <p style="margin-left: 15px">支持 JPG、PNG格式，图片小于50k</p>
            </FormItem>
          </Form>
        </div>
      </div>
      <div style="margin: 20px 0px 35px 25px; text-align: center!important;">
        <router-link :to="{ path: '/music'}">
          <Button style="width: 100px;height: 40px; ">返回</Button>
        </router-link>
        <Button type="primary" style="margin-left: 30px;width: 100px;height: 40px;" :loading="btnload.loading"
          @click="handleOk()">保存
        </Button>
      </div>

    </Card>
  </div>
</template>

<script lang="ts">
  import {Component, Vue} from 'vue-property-decorator';
  import {Route} from 'vue-router';
  import {FormBloc} from '@/view/music/FormBloc';
  import {isEmpty} from '@/base/util/Strings';
  import RoleSelector from '@/component/RoleSelector.vue';
  import {getValidateMaxString, getValidatePhone, getValidatePsd} from '@/base/util/Validate';
  import {Loading} from '@/base/Loading';
  import {baseUrl} from '@/base/Request';
  import {store} from '@/store/Store';

  @Component({components: {RoleSelector}})
  export default class extends Vue {
    beforeRouteEnter(to: Route, from: Route, next: (vm: any) => void) {
      next(vm => {
        if (!vm.isAdd) vm.bloc.getMusicById(vm.idx);
      });
    }

    get isAdd() {
      return !this.idx;
    }

    get idx() {
      return Number(this.$route.params.id);
    }

    bloc: FormBloc = new FormBloc();
    btnload = new Loading();

    ruleValidate = {
      musicName: [
        {required: true, message: '音乐名不能为空', trigger: 'blur'},
        {type: 'string', max: 15, message: '音乐名不能超过15个字', trigger: 'blur'}
      ],
      musicUrl: [
        {required: true, message: '音频文件不能为空', trigger: 'blur'}
      ],
      imgUrl: [
        {required: true, message: '图片文件不能为空', trigger: 'change'}
      ],
      code: [
        {required: true, message: '下发指令不能为空', trigger: 'blur'}
      ]
    };

    handleCancel() {
      this.$router.push({path: '/music'});
    }

    handleOk() {
      const formRef: any = this.$refs['formModel'];
      formRef.validate((valid) => {
        if (valid) {
            this.bloc.saveMusic().then(() => {
              this.handleCancel()
            })
          }
      });
    }

    imgUrl = '';
    visible = false;

    get fileList() {
      return this.bloc.fileList.map(x => {
        return {'name': 'name', 'modelIcon': x, 'status': 'finished'};
      });
    }

    handleView(url) {
      this.imgUrl = url;
      this.visible = true;
    }

    handleRemove(file) {
      this.bloc.fileList.splice(this.bloc.fileList.indexOf(file), 1);
      // this.bloc.model.modelIcon = ''
    }

    get uploadAudio() {
      return `${baseUrl}/api/upload/music/audio`
    }

    get uploadImg() {
      return `${baseUrl}/api/upload/music/img`
    }

    get uploadHeaders() {
      return {
        'Authorization': 'Bearer ' + store.state.auth.accessToken
      }
    }

    handleMaxSize(file) {
      this.$Message.error('图片大小不能超过50k')
    }

    handleFormatError(file) {
      this.$Message.error('请选择格式为JPG、PNG格式的文件')
    }

    handleBeforeUpload () {
      const check = this.bloc.fileList.length < 2;
      if (!check) {
        this.$Message.error('最多上传一张图片')
      }
      return check;
    }

    imgHandleSuccess(res, file) {
      this.bloc.form.imgUrl = res.data;
      this.bloc.fileList = []
      this.bloc.fileList.push(res.data)
    }
    audioHandleSuccess(res) {
      this.bloc.form.musicUrl = res.data
    }
  }
</script>

<style lang="less" scoped>
  .company-box {
    display: flex;
    justify-content: space-around;
  }

  .divider-short {
    width: 4px;
    height: 24px;
    background: #0079FE;
    margin-right: 10px;
  }

  .ivu-row-flex-middle {
    font-weight: bolder;
    font-size: 16px;
    margin-bottom: 28px;
  }

  .ivu-card-body > div {
    text-align: left !important;
  }

</style>
